<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="roleData"
        style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row :class="['bdbottom',index===0 ? 'bdtop':'']" v-for="(item1,index) in props.row.children"
                    :key="item1.id">
              <el-col :span="5">
                <el-tag>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[index2 !== 0 ? 'bdtop':'']" v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable
                            @close="removeRoleById(item3.id,props.row)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          label="#"
          type="index">
        </el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName">
        </el-table-column>
        <el-table-column
          label="角色描述"
          prop="roleDesc">
        </el-table-column>
        <el-table-column
          label="操作" width="300">
          <template slot-scope="scope">
            <!--  编辑按钮  -->
            <el-button type="primary" icon="el-icon-edit" size="mini"
            >编辑
            </el-button>
            <!--  删除按钮  -->
            <el-button type="text">
              <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-button>
            <!--  分配角色按钮  -->
            <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRoleRightDialog(scope.row)">
                分配权限
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--  分配权限的对话框  -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoleRightDialog"
      width="50%" @close="setDefRights">
      <el-tree
        :data="rightList"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        default-expand-all
        :default-checked-keys="defRights" ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleRightDialog = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        roleData: [],
        setRoleRightDialog: false,
        rightList: [],
        defaultProps: {
          children: 'children',
          label: 'authName'
        },
        defRights: [],
        roleId: ''
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      async getRolesList() {
        const {data} = await this.$http.get('roles')
        if (data.meta.status === 200) {
          this.roleData = data.data
        } else {
          return this.$message.error('获取角色列表失败')
        }

      },
      removeRoleById(rightId, role) {
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 调用删除接口
          const {data} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
          if (data.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            // this.getRolesList()
            // 只更新这个更改的角色的权限
            role.children = data.data
          } else {
            return this.$message.error('删除角色权限失败')
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // todo 方法名与属性名不能同名
      async showRoleRightDialog(role) {
        this.roleId = role.id
        // 获取树形结构的权限列表
        const {data} = await this.$http.get('rights/tree')
        if (data.meta.status === 200) {
          this.rightList = data.data
        } else {
          this.$message.error('获取用户权限失败')
        }

        // 根据角色获取权限
        this.getDefRights(role, this.defRights)
        console.log(data)
        this.setRoleRightDialog = true
      },
      // 通过递归的形式 获取角色下所有的三级权限的id 并保存到defRights数组中
      getDefRights(node, arr) {
        //如果当前节点不包含children属性，那么他就是三级权限
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach(item => {
          this.getDefRights(item, arr)
        })

      },
      // 监听对话框的关闭，重置默认defRights数组值
      setDefRights() {
        this.defRights = [];
      },
      //为角色分配权限
      async allotRights() {
        // 获取被选中的节点 和 半选中节点
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        console.log(keys)
        const idStr = keys.join(',')
        console.log(idStr)
        const {data} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
        console.log(data)
        if (data.meta.status === 200) {
          this.$message.success('分配权限成功')
          this.getRolesList()
          this.setRoleRightDialog = false

        }else{
          this.$message.error('分配权限失败')
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }
</style>
